const vscode = require('vscode');
const fs = require('fs/promises');
// const path = require('path');

// 查找 SCSS 文件
async function findSCSSFile() {
    const workspaceFolders = vscode.workspace.workspaceFolders;
    if (!workspaceFolders) {
        vscode.window.showWarningMessage('未找到工作区文件夹');
        return null;
    }

    const scssFiles = await vscode.workspace.findFiles('**/xyBright.scss');
    if (scssFiles.length === 0) {
        // vscode.window.showWarningMessage('未找到 xyBright.scss 文件');
        return null;
    }

    return scssFiles[0].fsPath;
}

// 解析 SCSS 文件中的类名和样式
async function parseSCSSClasses() {
    const scssFilePath = await findSCSSFile();
    if (!scssFilePath) {
        return {};
    }

    try {
        const scssContent = await fs.readFile(scssFilePath, 'utf-8');
        const classes = {};

        // 解析普通类名
        const classRegex = /\.([\w-]+)\s*\{([^}]+)\}/g;
        let match;
        while ((match = classRegex.exec(scssContent))!== null) {
            const className = match[1].trim();
            const classStyle = match[2].trim();
            classes[className] = classStyle;
        }

        // 解析 @for 循环生成的类名
        // const forLoopRegex = /@for \$(\w+) from (\d+) through (\d+) \{\s*\.([\w-]+#\{\$\1\})\s*\{([^}]+)\}/g;
        const forLoopRegex =  /@for \$(\w+) from (\d+) through (\d+) \{\s*\.([\w-]+#\{\$\1\})\s*\{((?:[^{}]+|\{[^{}]*\})*)\}/g;
        let forMatch;
        while ((forMatch = forLoopRegex.exec(scssContent))!== null) {
            const variable = forMatch[1];
            const start = parseInt(forMatch[2], 10);
            const end = parseInt(forMatch[3], 10);
            const classTemplate = forMatch[4];
            const styleTemplate = forMatch[5];
            // 获取倍数和单位
            const number = extractTextBetweenAsteriskAndBrace(forMatch[0])
            const unit = extractCharsBetweenBracesAndSemicolon(forMatch[5])
            for (let i = start; i <= end; i++) {
                // @ts-ignore
                const className = classTemplate.replace(`#{$${variable}}`, i);
                // 确保插值表达式被正确替换
                // @ts-ignore
                const classStyle = styleTemplate.replace(new RegExp(`#\{\\$${variable}\\}`, 'g'), i);
                // const lineClassStyle = `${classStyle.split(':')[0]}: ${classStyle.indexOf('2')!== -1? i * 2 : i}px;`
                const lineClassStyle = `${classStyle.split(':')[0]}:${number? i*number : i}${unit};`
                classes[className] = lineClassStyle;
            }
        }
        return classes;
    } catch (error) {
        vscode.window.showErrorMessage(`读取 SCSS 文件时出错: ${error.message}`);
        return {};
    }
}
function extractTextBetweenAsteriskAndBrace(str) {
    const regex = /\*(.*?)\}/;
    const match = str.match(regex);
    if (match && match[1]) {
        return match[1];
    }
    return '';
}
function extractCharsBetweenBracesAndSemicolon(str) {
    const regex = /}(.*?);/g;
    const matches = [];
    let match;
    while ((match = regex.exec(str))!== null) {
        matches.push(match[1].trim());
    }
    return matches.length > 0 ? matches[0] : null;
}
// 生成悬停提示内容
function generateHoverContent(word, classStyle) {
    // 移除首尾空格
    classStyle = classStyle.trim();
    // 处理换行符和缩进，让样式展示更美观
    const formattedStyle = classStyle.split(';').map(style => {
        style = style.trim();
        if (style) {
            return `  ${style};`;
        }
        return '';
    }).filter(Boolean).join('\n');

    return `\`\`\`scss\n.${word} {\n${formattedStyle}\n}\n\`\`\``;
}

// 注册悬停提示提供者
function registerHoverProvider() {
    vscode.languages.registerHoverProvider(['html', 'vue'], {
        provideHover: async (document, position) => {
            const classes = await parseSCSSClasses();
            const wordRange = document.getWordRangeAtPosition(position, /[\w-]+/);
            if (!wordRange) {
                return null;
            }
            const word = document.getText(wordRange);
            if (classes[word]) {
                const hoverContent = generateHoverContent(word, classes[word]);
                return new vscode.Hover(hoverContent);
            }
            return null;
        }
    });
}

// 注册类名下划线装饰器
function registerClassUnderlineDecorator() {
    const decorationType = vscode.window.createTextEditorDecorationType({
        textDecoration: 'underline'
    });

    const updateDecorations = async (editor) => {
        if (!editor) {
            return;
        }
        const classes = await parseSCSSClasses();
        const text = editor.document.getText();
        const decorations = [];

        // 匹配 class 属性内的类名
        const classAttributeRegex = /class="([\w-\s]+)"/g;
        let classAttributeMatch;
        while ((classAttributeMatch = classAttributeRegex.exec(text))!== null) {
            const classAttributeValue = classAttributeMatch[1];
            const classNames = classAttributeValue.split(/\s+/);
            for (const className of classNames) {
                if (classes[className]) {
                    const startIndex = classAttributeMatch.index + classAttributeMatch[0].indexOf(className);
                    const endIndex = startIndex + className.length;
                    const startPos = editor.document.positionAt(startIndex);
                    const endPos = editor.document.positionAt(endIndex);
                    const decoration = { range: new vscode.Range(startPos, endPos) };
                    decorations.push(decoration);
                }
            }
        }

        editor.setDecorations(decorationType, decorations);
    };

    vscode.window.onDidChangeActiveTextEditor(editor => {
        if (editor && ['html', 'vue'].includes(editor.document.languageId)) {
            updateDecorations(editor);
        }
    });

    vscode.workspace.onDidChangeTextDocument(event => {
        const editor = vscode.window.activeTextEditor;
        if (editor && editor.document === event.document && ['html', 'vue'].includes(editor.document.languageId)) {
            updateDecorations(editor);
        }
    });

    const activeEditor = vscode.window.activeTextEditor;
    if (activeEditor && ['html', 'vue'].includes(activeEditor.document.languageId)) {
        updateDecorations(activeEditor);
    }
}

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {
    registerHoverProvider();
    registerClassUnderlineDecorator();
}

function deactivate() {}

module.exports = {
    activate,
    deactivate
};    